package org.flow.basic.thread;

import org.flow.basic.junit.ThreadLocalVar;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;
import java.util.stream.Collectors;

/**
 * @author xl-9527
 * @since 2024/7/28
 **/
public class ThreadLocalTestDemo {

    public static final ExecutorService POOL = Executors.newFixedThreadPool(3);
    private static final Logger log = LoggerFactory.getLogger(ThreadLocalTestDemo.class);

    public static void main(String[] args) {
        final List<CompletableFuture<Map<String, Integer>>> completableFutures = new ArrayList<>();

        for (int i = 0; i < 10; i++) {
            completableFutures.add(CompletableFuture.supplyAsync(() -> {
                final ThreadLocal<Integer> threadLocal = ThreadLocalVar.THREAD_LOCAL;
                threadLocal.set(threadLocal.get() + 1);
                return Map.of(Thread.currentThread().getName(), threadLocal.get());
            }, POOL));
        }

        CompletableFuture.allOf(completableFutures.toArray(new CompletableFuture[0]));

        final Map<String, Integer> collect = completableFutures.stream().map(v -> {
            try {
                return v.get(1, TimeUnit.SECONDS);
            } catch (InterruptedException | ExecutionException | TimeoutException e) {
                throw new RuntimeException(e);
            }
        }).collect(Collectors.toMap(v -> v.keySet().iterator().next(), v -> v.values().iterator().next(), Integer::max));

        collect.forEach((key, val) -> log.info("key -> {}, val -> {}", key, val));

        POOL.shutdownNow();
    }
}
